(function () {//String的一些扩展
    "use strict";
    window.console=window.console||{//如果不支持console，就alert
        log:function(){}//window.alert
    };
    /**
     * 字符串去除左右两端的空白字符
     * " sadfsw saf ".trim() 结果为："sadfsw saf"
     */
    String.prototype.trim = function () {
        return this.replace(/(^\s*)|(\s*$)/g, '');
    }
    /**
     * 字符串数组去重
     */
    Array.prototype.distinct = function () {
        var obj = {}, arr = [], i = 0, len = this.length, n;
        for (; i < len; i++) {
            n = this[i];
            if (obj[n] !== true) {
                obj[n] = true;
                arr.push(n);
            }
        }
        return arr;
    }
    window.store = (function () {//本地存储API
        var api = {set: $.noop, get: $.noop, remove: $.noop, clear: $.noop},
            win = window,
            doc = win.document,
            localStorageName = 'localStorage',
            globalStorageName = 'globalStorage',
            storage;
        try {
            if (localStorageName in win && win[localStorageName]) {
                storage = win[localStorageName];
                api.set = function (key, val) {
                    storage.setItem(key, val)
                };
                api.get = function (key) {
                    return storage.getItem(key)
                };
                api.remove = function (key) {
                    storage.removeItem(key)
                };
                api.clear = function () {
                    storage.clear()
                };
                return api;
            }
        } catch (e) {
            console.log(e);
        }
        if (globalStorageName in win && win[globalStorageName]) {
            storage = win[globalStorageName][win.location.hostname];
            api.set = function (key, val) {
                storage[key] = val
            };
            api.get = function (key) {
                return storage[key] && storage[key].value
            };
            api.remove = function (key) {
                delete storage[key]
            };
            api.clear = function () {
                for (var key in storage) {
                    delete storage[key]
                }
            };
            return api;
        }
        if (doc.documentElement.addBehavior) {
            var getStorage = function () {
                if (storage) {
                    return storage
                }
                storage = doc.body.appendChild(doc.createElement('div'));
                storage.style.display = 'none';
                // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
                // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
                storage.addBehavior('#default#userData');
                storage.load(localStorageName);
                return storage;
            }

            api.set = function (key, val) {
                var storage = getStorage();
                storage.setAttribute(key, val);
                storage.save(localStorageName);
            };
            api.get = function (key) {
                var storage = getStorage();
                return storage.getAttribute(key);
            };
            api.remove = function (key) {
                var storage = getStorage();
                storage.removeAttribute(key);
                storage.save(localStorageName);
            }
            api.clear = function () {
                var storage = getStorage();
                var attributes = storage.XMLDocument.documentElement.attributes;
                storage.load(localStorageName);
                for (var i = 0, attr; attr = attributes[i]; i++) {
                    storage.removeAttribute(attr.name);
                }
                storage.save(localStorageName);
            }
            return api;
        }
    })();
})();
/**
 * 公用的一些函数，jquery扩展
 * @charset utf8
 * @autor liujhc
 */
(function($){
    //禁用ajax缓存
    $.ajaxSetup({
        cache:false
    });
    $.extend({
        /**
         * 包装函数，支持在函数前后加入其他代码，返回新的函数
         * @param target 要包装的函数
         * @param before 在func执行之前执行的函数
         * @param after 在func执行后执行的函数
         * @return 返回经过包装后的函数，并附带了target原来的属性
         */
        wrap:function(target,before,after){
            return $.extend(function(){
                var result;
                if($.isFunction(before)){
                    before.apply(this,arguments);
                }
                if($.isFunction(target)){
                    result =target.apply(this,arguments);
                }
                if($.isFunction(after)){
                    after.apply(this,arguments);
                }
                return result;
            },target);
        },
        /**
         * 加载js
         */
        loadScript:function(url){
            document.write("<script type='text/javascript' src='"+url+"'><\/script>");
        },
        /**
		 * 将复杂js对象转换成url参数
		 */
        param: function( a, traditional ) {
            var s = [],
            add = function( key, value ) {
                // If value is a function, invoke it and return its value
                value = jQuery.isFunction( value ) ? value() : value;
                s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value==null?"":value );
            };

            // Set traditional to true for jQuery <= 1.3.2 behavior.
            if ( traditional === undefined ) {
                traditional = jQuery.ajaxSettings.traditional;
            }

            // If an array was passed in, assume that it is an array of form elements.
            if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
                // Serialize the form elements
                jQuery.each( a, function() {
                    add( this.name, this.value );
                });

            } else {
                // If traditional, encode the "old" way (the way 1.3.2 or older
                // did it), otherwise encode params recursively.
                for ( var prefix in a ) {
                    buildParams( prefix, a[ prefix ], traditional, add );
                }
            }

            // Return the resulting serialization
            return s.join( "&" ).replace( /%20/g, "+" );
        },
        /**
         * 在构建正则表达式之前，将字符串中的关键字符替换，以免影响正则表达式的含义
         */
        preRegexp:function(str){
            return str.replace(/[\"\'\\\*\+\?\.\,\|\&\^\$\(\)\{\}\[\]]/g,function(c){
                return "\\"+c;
            });
        },
        /**
         * js模板引擎
         * @param template
         * @param data
         */
        template:function(template,data){
            return template.replace(/\${\s?(\w*?)\s?}/igm,function($,$1){
                return  data[$1]||$;
            });
        }
    });
    function buildParams( prefix, obj, traditional, add ) {
        if ( jQuery.isArray( obj ) ) {
            // Serialize array item.
            jQuery.each( obj, function( i, v ) {
                if ( traditional || /\[\]$/.test( prefix ) ) {
                    add( prefix, v );
                } else {
                    buildParams( prefix + ( typeof v === "object" || jQuery.isArray(v) ? "[" + i + "]": "" ) , v, traditional, add );
                }
            });

        } else if ( !traditional && obj != null && typeof obj === "object" ) {
            // Serialize object item.
            for ( var name in obj ) {
                buildParams( prefix + "['" + encodeURIComponent(name) + "']", obj[ name ], traditional, add );
            //buildParams( prefix + "." + name, obj[ name ], traditional, add );
            }
        } else {
            // Serialize scalar item.
            add( prefix, obj );
        }
    }
    /**
	 * jQuery扩展
	 */
    $.fn.extend({
        /**
		 * 自动填充表单,支持类似form.userName这样的属性映射，
		 * 例如：如需填充name='form.userName'的表单元素，传入下面两种结构的json对象都可以准确映射：
		 * {'form.userName':'Tom'}或{form:{userName:"Tom"}}
		 */
        fillForm:function(data){
            if(data && typeof data=="object"){
                this.find(":input:not(:button)").andSelf().filter(":input[name]").each(function(){
                    var $field=$(this), key = $field.attr("name"), value = data[key];
                    if (value === undefined) {
                        try { // 多层获取
                            value = eval("data." + key);
                        } catch (e) {
                        }
                    }
                    if(value!=null){
                        // checkbox 和 radio 必须传入数组
                        if (!$.isArray(value) && $field.is(":checkbox,:radio")) {
                            $field.val([value]);
                        } else {
                            $field.val(value.length == 0 ? "" : value);
                        }
                        if($field.is(":checked,select")){
                            $field.change();
                        }
                    }
                });
            }
            return this;
        },
        resetForm:function(){//jQuery.form.js插件的resetForm方法有bug，在此重写
            this.each(function(){
                if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
                    this.reset();
                }
            }).find(":input:not(:button)").each(function(){
                $(this).val($(this).val());
            });
            return this;
        },
        /**
		 * 对于所选元素进行排序
		 * @parent sortby 排序方法
		 * 例如,对select的选项按名称排序:
		 * $("select:eq(0) option").sort(function(a,b){
		 *    var ta=$(a).text(), tb=$(b).text();
		 *    return ta>tb?1:(ta<tb?-1:0);
		 * });
		 */
        sort:function(sortby){
            var $parent = this.parent();
            if(!sortby){//默认用文本排序
                sortby=function(a,b){
                    var ta=$(a).text(), tb=$(b).text();
                    return ta>tb?1:(ta<tb?-1:0);
                }
            }
            $.each(this.get().sort(sortby),function(){
                $parent.append(this);
            })
            return this;
        },
        /**
		 * 获取被选内容中的表单数据
		 */
        formData:function(){
            var result={}, $form=$(this);
            $form.find(":input[name]").andSelf().filter(":input:not(:button,:checkbox,:radio)[name],:checked[name]").each(function(){
                var $field=$(this), val=[], name=$field.attr("name");
                if($field.is("select")){
                    $field.find("option[value]:selected").each(function(){
                        val.push($(this).attr("value"));
                    });
                }else{
                    val.push($field.attr("value"));
                }
                result[name] = result[name] ? result[name].concat(val) : val;
            });
            return result;
        },
        /**
         * 可输入的下拉列表
         */
        inputSelect:function (options) {
            var defaultOption = {
                option: "input"
            };
            options = $.extend(defaultOption, options);
            this.each(function () {
                var $current = $(this);
                $current.css({
                    "marginLeft": "-150px",
                    "position": "relative"
                }).wrap("<span></span>").wrap("<span></span>");
                var $parent = $current.parent().css({
                    marginLeft:150,
                    overflow:"visible"
                }).parent().css({
                    position: "relative",
                    display: "inline-block",
                    width:$current.width()+3
                });
                var $input = $("<input name='"+($current.attr("name")||"")+"_input' type='text'/>").css({
                    position:"absolute",
                    left:1,
                    top:2,
                    border:"none",
                    display:"none",
                    height:$current.height()-3,
                    width:$current.width() - 20
                });
                $input.appendTo($parent).blur(function(){
                    var val = $(this).val();
                    if(val==""){
                        $input.hide();
                        $current.children(":first").attr("selected","selected");
                    }else{
                        $current.children().each(function(){
                            if($(this).attr("value")!=options.option && $(this).text()==val){
                                $input.hide();
                                $(this).attr("selected","selected");
                                $current.select();
                                return false;
                            }
                        });
                    }
                });
                $current.height($current.height()+3).change(function(){
                    if($current.children("option:selected").attr("value")==options.option){
                        $input.show().select();
                    }else{
                        $input.hide();
                    }
                });
            });
            return this;
        },
        /**
         *
         * @param callback 第一个参数是iframe的contentWindow， 第二个参数是contentDocument
         * @returns {*}
         */
        iframeReady: function (callback) {
            this.each(function () {
                var _this = this;
                if ($(_this).is("iframe")) {
                    var doc = _this.contentWindow.document;
                    if (doc.readyState === 'complete' && doc.body && doc.body.hasChildNodes()) {
                        callback.call(_this, _this.contentWindow, _this.contentWindow.document);
                    } else {
                        $(this).bind('load', function () {
                            callback.call(_this, _this.contentWindow, _this.contentWindow.document);
                        });
                    }
                }
            });
            return this;
        },
        /**
         * 自适应iframe高度
         * @returns {*}
         */
        iframeAutoHeight: function (adaptive) {
            this.each(function () {
                var $frame = $(this);
                $frame.bind('autoHeight',function () {
                    $(this).iframeReady(function (wind, doc) {
                        var height = 0;
                        $('body', doc).children(':visible').each(function () {
                            height += $(this).height();
                        });
                        $frame.height(height);
                    });
                }).trigger('autoHeight');
                if (adaptive) {
                    $frame.iframeReady(function (win, doc) {
                        $('body', doc).bind('click keyup', function () {
                            $frame.trigger('autoHeight');
                        });
                    });
                }
            });
            return this;
        }
    });

    $(function(){
        /*
		 * 页面框架的右上角按钮功能
		 */
        $(".frame>.frame-head:has(.frame-button.plus) + .frame-content").hide();

        $(".frame>.frame-head>.frame-button").live("click", function () {
            var $fb = $(this);
            var callback = function () {
                $(window).triggerHandler('resize');
            };
            if ($fb.hasClass("plus")) {
                $fb.removeClass("plus").addClass("minus").parent().next(".frame-content").slideDown("normal", callback);
            } else if ($fb.hasClass("minus")) {
                $fb.removeClass("minus").addClass("plus").parent().next(".frame-content").slideUp("normal", callback);
            } else if ($fb.hasClass("close")) {
                $fb.parentsUntil('.frame').parent().remove();
                $(window).triggerHandler('resize');
            }
        });

        $(".ui-dialog-content .btn-dialog-cancel").live("click",function(){//当点击对话框中的取消按钮时，关闭该对话框
            $(this).parents(".ui-dialog-content").dialog("close");
        });
        $("select.input-select").inputSelect();
    });
})(jQuery);